package com.uni.controller;

import com.uni.base.RestResponse;
import com.uni.pojo.Address;
import com.uni.pojo.User;
import com.uni.service.RoleService;
import com.uni.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/2/7 14:57
 **/
@Controller
public class RegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @GetMapping("/register.html")
    public String toRegister(){
        return "register";
    }
    // 用户注册
    @PostMapping("/register")
    @ResponseBody
    public String register(User user, Address addr, @RequestParam("checkcode") String inputCode, HttpSession session){
        String realCode = (String) session.getAttribute("code");
        if(!realCode.equals(inputCode)) return RestResponse.fail("验证码错误!").toJSONString();
        user.setAddressDetail(addr);

        User userInfo = roleService.setRole(userService.register(user), 2);
        if(userInfo != null) session.setAttribute("userInfo", userInfo);
        return userInfo != null ?
                RestResponse.ok("注册成功!").toJSONString()
                : RestResponse.fail("注册失败.").toJSONString();
    }

}
